package com.zzld.modules.common.action;


import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zzld.core.common.config.GlobalStatic;
import com.zzld.core.utils.CaptchaUtils;
import com.zzld.modules.wechat.WeChat;
import com.zzld.modules.wechat.bean.UserInfo;
import com.zzld.modules.wechat.oauth.Oauth;
import com.zzld.modules.wechat.oauth.User;
import com.zzld.modules.wxsys.entity.WXAccount;
import com.zzld.modules.wxsys.entity.WXaccesstoken;
import com.zzld.modules.wxsys.service.IWXAccesstokenService;
import com.zzld.modules.wxsys.service.IWXAccountService;


@Controller
public class Commonctl {
	
	@Autowired
	private IWXAccountService wxAccountService;
	
	@Autowired
	private IWXAccesstokenService wxaccesstokenService;
	
	/** 调用jsp页面 **/
    
    @RequestMapping(value = "${frontPath}")
    public String f(Model model){
    	return "index";
    }
    
    @RequestMapping(value = "/jsp/{name}")
	public String jsp(@PathVariable String name) {
		return "/" + name;
	}

	@RequestMapping(value = "/jsp/{path}/{name}")
	public String jsp(@PathVariable String path, @PathVariable String name,
			Model model) {
		return "/" + path + "/" + name;
	}

	@RequestMapping(value = "/jsp/{pathA}/{pathB}/{name}")
	public String jsp(@PathVariable String pathA, @PathVariable String pathB,
			@PathVariable String name) {
		return "/" + pathA + "/" + pathB + "/" + name;
	}
    
	
	@RequestMapping(value = "/weixin/hdsq")
	public void test(Model model, HttpServletRequest request,HttpServletResponse response) {
		Oauth oauthInfo=new Oauth();
		String code=request.getParameter("code");
		String result="";
		String url="http://auto.nxsh114.com:8090/game/get_code";
		try {
			//根据code换取临时access_token
			result=oauthInfo.getToken(code);
			JSONObject token_json= JSON.parseObject(result);
			String openid=token_json.getString("openid");
			User wxuser=new User();
			WXAccount wxaccount=wxAccountService.findwxaccount(oauthInfo.getAppid(),oauthInfo.getSecret());
			if(wxaccount!=null){
				String accessToken=getExistAccessToken(wxaccount.getAcccountId());
				if(StringUtils.isNotBlank(accessToken)){
					UserInfo wxUserInfo=wxuser.getUserInfo(accessToken, openid);
					if(wxUserInfo.getSubscribe()==1){
						url=url+"?openid="+openid;
					}
				}
			}
			response.sendRedirect(url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/weixin/hdsq/checkSubscribe")
	@ResponseBody
	public boolean checkSubscribe(Model model, HttpServletRequest request,HttpServletResponse response) {
		Oauth oauthInfo=new Oauth();
		String openid=request.getParameter("openid");
		boolean result=false;
		try {
			User wxuser=new User();
			WXAccount wxaccount=wxAccountService.findwxaccount(oauthInfo.getAppid(),oauthInfo.getSecret());
			if(wxaccount!=null){
				String accessToken=getExistAccessToken(wxaccount.getAcccountId());
				if(StringUtils.isNotBlank(accessToken)){
					UserInfo wxUserInfo=wxuser.getUserInfo(accessToken, openid);
					if(wxUserInfo.getSubscribe()==1){
						result=true;
					}
				}
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	
	//获取有效的accesstoken
		public String getExistAccessToken(String wxaccount){
			//从数据库读取accesstoken
			String token=null;
			try {
				WXaccesstoken wxaccesstoken=wxaccesstokenService.selectByPrimaryKey(wxaccount);
				if(wxaccesstoken!=null){
					//获取原有的token
					token=wxaccesstoken.getAccesstoken();
					Date accessExpires= wxaccesstoken.getAccessexpires();
					Date nowdate=new Date();  
				    int index=nowdate.compareTo(accessExpires);
				    System.out.println("index>0:"+(index>0));
					if(index>0){
						token=getNewAccesstoken(wxaccount,false);
					}
				}else{
					//获取新的token
					token=getNewAccesstoken(wxaccount,true);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        return token;
		}
		
		/**
		 * 重新获取一个全局token保存到数据库
		 * @return
		 */
		public String getNewAccesstoken(String wxAccount,boolean isNew){ 
			//重新获取
			String token=null;
			try {
				token = WeChat.getAccessToken();
				if(StringUtils.isNotBlank(token)){
					WXaccesstoken entity=new WXaccesstoken();
					entity.setAccesstoken(token);
					long timeout=System.currentTimeMillis()+7200*1000;
				    Calendar cal = Calendar.getInstance();
			        cal.setTimeInMillis(timeout);
			        Date time_date = cal.getTime();
			        
					entity.setAccessexpires(time_date);
					entity.setWxAccount(wxAccount);
					if(isNew){
						wxaccesstokenService.saveSelective(entity);
					}else{
						wxaccesstokenService.updateByPrimaryKeySelective(entity);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return token;
		}
    
    
    /**
	 * 生成验证码
	 * 
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/getCaptcha")
	public void getCaptcha(HttpSession session,HttpServletResponse response) throws IOException {

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.IMAGE_JPEG);

		CaptchaUtils tool = new CaptchaUtils();
		StringBuffer code = new StringBuffer();
		BufferedImage image = tool.genRandomCodeImage(code);
		session.removeAttribute(GlobalStatic.DEFAULT_CAPTCHA_PARAM);
		session.setAttribute(GlobalStatic.DEFAULT_CAPTCHA_PARAM, code.toString());

		// 将内存中的图片通过流动形式输出到客户端
		ImageIO.write(image, "JPEG", response.getOutputStream());
		return;
	}
	
}
